package org.ofbiz.sys;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javolution.util.FastList;
import javolution.util.FastMap;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ofbiz.sys.utils.ApiResponse;
import org.ofbiz.sys.utils.Constants;
import org.ofbiz.sys.utils.JsonObjectUtils;
import org.ofbiz.sys.utils.PayUtil;
import org.ofbiz.sys.utils.ResponseCode;
import org.ofbiz.sys.utils.ResponseUtils;
import org.ofbiz.sys.utils.TokenUtil;
import org.ofbiz.base.crypto.HashCrypt;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.webapp.event.EventHandlerException;
import org.ofbiz.webapp.event.FileUploadProgressListener;

import com.google.gson.Gson;

/** 
 *
 */
public class AdminEvents {
    private static final String module = AdminEvents.class.getName();

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static String invoke(HttpServletRequest request, HttpServletResponse response) throws EventHandlerException {
	LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
	Delegator delegator = (Delegator) request.getAttribute("delegator");
	DispatchContext dctx = dispatcher.getDispatchContext();
	Locale locale = UtilHttp.getLocale(request);
	TimeZone timeZone = UtilHttp.getTimeZone(request);
	// place holder for the content id
	String pathInfo = request.getPathInfo();
	String serviceName = "";
	String judgment = "";
	String judgment2 = "";
	try {
	    if (pathInfo != null) {// targetRequest.equals(actualRequest) &&
		String[] pathParsed = pathInfo.split("/");
		if (pathParsed.length > 5) {
		    serviceName = pathParsed[5];
		    judgment = pathParsed[4];
		    judgment2 = pathParsed[3];
		} else if (pathParsed.length > 4) {
		    serviceName = pathParsed[4];
		    judgment = pathParsed[3];
		    judgment2 = pathParsed[2];
		} else if (pathParsed.length > 3) {
		    serviceName = pathParsed[3];
		    judgment = pathParsed[2];
		    judgment2 = pathParsed[1];
		} else if (pathParsed.length > 2) {
		    serviceName = pathParsed[2];
		    judgment = pathParsed[1];
		} else {
		    serviceName = pathParsed[1];
		}
	    }

	    Map<String, Object> serviceContext = FastMap.newInstance();

	    if (judgment.equals("user")) {
		String sessionId = request.getSession().getId();
		String sessionKey = TokenUtil.getTokenId(sessionId);
		serviceContext.put("sessionKey", sessionKey);
		serviceContext.put("request", request);
		serviceContext.put("response", response);
	    }

	    if (judgment.equals("request")) {
		serviceContext.put("request", request);
		serviceContext.put("response", response);
	    }

	    if (judgment.equals("upload")) {
		Map<String, Object> multiPartMap = checkRequestMultiPart(request);
		System.out.println("multiPartMap=====" + multiPartMap);
		serviceContext.putAll(multiPartMap);
	    }
	    Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null);
	    serviceContext.putAll(rawParametersMap);
	    Map<String, Object> rawAttributeMap = UtilHttp.getAttributeMap(request);
	    serviceContext.putAll(rawAttributeMap);

	    // 后期此处代码需要优化
	    String token = request.getHeader("X-Access-Token");
	    if (UtilValidate.isNotEmpty(token)) {
		serviceContext.put("sessionKey", token);
	    }
	    Debug.logInfo("serviceName for Alias: " + serviceName, module);

	    if (judgment2.equals("dict") && judgment.equals("getDictItems")) {
		serviceContext.put("dictId", serviceName);
		serviceName = "getDictItems";
	    }
	    if (judgment2.equals("dict") && judgment.equals("loadDict")) {
		serviceContext.put("dictId", serviceName);
		serviceName = "getDictItems";
	    }
	    // 不需要签名验证
	    if (!judgment.equals("sha") && !judgment.equals("import") && !judgment.equals("dict") && !judgment.equals("upload")
		    && !judgment2.equals("special") && !judgment.equals("test") && !serviceName.equals("randomImage")) {
		String sign = (String) serviceContext.get("sign");
		String signMessage = validateSign(request, sign);
		if (signMessage == "error") {
		    Debug.logError("sign validate error", module);
		    return sendError(response, request, "sign validate error");
		}
	    }
	    
	    //sha加密验证
	    if (judgment.equals("sha")){
		String sign = (String) serviceContext.get("sign");
		String signMessage = validateSha(request, sign);
		if (signMessage == "error") {
		    Debug.logError("sign validate error", module);
		    return sendError(response, request, "sign validate error");
		}
	    }
	    
	    if ("public".equals(judgment)) {
		Map<String, Object> map = FastMap.newInstance();
		Iterator it = serviceContext.entrySet().iterator();
		while (it.hasNext()) {
		    Map.Entry entry = (Map.Entry) it.next();
		    if (!entry.getKey().equals("entityName") && !entry.getKey().equals("column")
			    && !entry.getKey().equals("superQueryParams")
			    && !entry.getKey().equals("superQueryMatchType") && !entry.getKey().equals("order")
			    && !entry.getKey().equals("field") && !entry.getKey().equals("autoHeadId")
			    && !entry.getKey().equals("pageNo") && !entry.getKey().equals("pageSize")
			    && !entry.getKey().equals("autoParentHeadId") && !entry.getKey().equals("appId")
			    && !entry.getKey().equals("nonce_str") && !entry.getKey().equals("_site_id_param")
			    && !entry.getKey().equals("sessionKey") && !entry.getKey().equals("sign")
			    && !entry.getKey().toString().contains("List-")) {
			map.put("inputFields_" + entry.getKey(), entry.getValue());
			serviceContext.remove(entry.getKey());
		    } else if (entry.getKey().toString().contains("List-")) {
			serviceContext.put((String) entry.getKey(), entry.getValue());
		    }
		}
		serviceContext.putAll(map);
	    }

	    // 二次处理参数
	    serviceContext = JsonObjectUtils.mapInHandle(serviceContext);

	    ModelService model = dctx.getModelService(serviceName);
	    GenericValue userLogin = null;
	    if (model == null) {
		Debug.logError("Could not find Service [" + serviceName + "].", module);
		return sendError(response, request, "Problem processing the service");
	    }

	    if (model.auth) {
		String sessionKey = (String) serviceContext.get("sessionKey");
		GenericValue userLoginToken = delegator.findOne("UserLoginToken",
			UtilMisc.toMap("sessionKey", sessionKey), false);
		if (UtilValidate.isNotEmpty(userLoginToken)) {
		    userLogin = delegator.findOne("UserLogin",
			    UtilMisc.toMap("userLoginId", userLoginToken.getString("userLoginId")), false);
		} else {
		    String newUsername = (String) serviceContext.get("login.username");
		    String newPassword = (String) serviceContext.get("login.password");
		    if (UtilValidate.isNotEmpty(newUsername) && UtilValidate.isNotEmpty(newUsername)) {
			Map loginResult = dispatcher.runSync("userLogin",
				UtilMisc.toMap("login.username", newUsername, "login.password", newPassword));// ,
													      // "locale",
													      // Locale.CHINESE
			Debug.log(loginResult.toString(), module);
			if (ServiceUtil.isSuccess(loginResult)) {
			    userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", newUsername),
				    false);
			}
			if (UtilValidate.isEmpty(userLogin)) {
			    if (serviceName.equals("getLogOut")) {
				String body = "{}";
				ApiResponse apiResponse = new ApiResponse(request, body, "success", "0");
				ResponseUtils.renderApiJson(response, request, apiResponse);
				return "success";
			    } else {
				return sendError(response, request,
					"Problem processing the service, check your USERNAME and PASSWORD.");
			    }
			}
		    } else {
			if (serviceName.equals("getLogOut")) {
			    String body = "{}";
			    ApiResponse apiResponse = new ApiResponse(request, body, "success", "0");
			    ResponseUtils.renderApiJson(response, request, apiResponse);
			    return "success";
			} else {
			    return sendError(response, request,
				    "Problem processing the service, check your USERNAME and PASSWORD.");
			}
		    }

		}
	    }

	    List<Object> errorMessages = FastList.newInstance();
	    serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone,
		    locale);
	    if (errorMessages.size() > 0) {
		return sendError(response, request, "Problem processing the serviceContext Valid," + errorMessages);
	    }
	    // include the UserLogin value object
	    if (userLogin != null) {
		serviceContext.put("userLogin", userLogin);
	    }
	    // include the Locale object
	    if (locale != null) {
		serviceContext.put("locale", locale);
	    }
	    // include the TimeZone object
	    if (timeZone != null) {
		serviceContext.put("timeZone", timeZone);
	    }

	    response.setContentType("application/json");
	    Debug.logVerbose("[Processing]: REST Event", module);

	    if (judgment.equals("export")) {
		ExeclEvents excelEvents = new ExeclEvents();
		request.setAttribute("serviceName", serviceName);
		request.setAttribute("serviceContext", serviceContext);
		return excelEvents.exportExcel(request, response);
	    }
	    if (judgment.equals("import")) {
		ExeclEvents excelEvents = new ExeclEvents();
		Map<String, Object> multiPartMap = checkRequestMultiPart(request);
		serviceContext.putAll(multiPartMap);
		request.setAttribute("serviceName", serviceName);
		request.setAttribute("serviceContext", serviceContext);
		return excelEvents.importExcel(request, response);
	    }

	    Map<String, Object> serviceResults = dispatcher.runSync(serviceName, serviceContext);
	    Debug.logVerbose("[EventHandler] : Service invoked", module);

	    serviceResults.remove("responseMessage");

	    serviceResults = JsonObjectUtils.optimizingResults(serviceResults);
	    String message = null;
	    String code = null;

	    if (UtilValidate.isNotEmpty(serviceResults.get("errorMessage"))) {
		message = (String) serviceResults.get("errorMessage");
		message = message.replaceAll(",", ";");
		message = message.replaceAll("\"", "'");
		serviceResults.remove("errorMessage");
		code = ResponseCode.API_CODE_CALL_FAIL;
	    }
	    if (UtilValidate.isNotEmpty(serviceResults.get("errorMessageList"))) {
		List<Object> errorMessageList = (List<Object>) serviceResults.get("errorMessageList");
		message = (String) errorMessageList.get(0);
		message = message.replaceAll(",", ";");
		message = message.replaceAll("\"", "'");
		serviceResults.remove("errorMessageList");
		code = ResponseCode.API_CODE_CALL_FAIL;
	    }
	    if (UtilValidate.isNotEmpty(serviceResults.get("authCode"))) {
		code = (String) serviceResults.get("authCode");
		serviceResults.remove("authCode");
	    } else {
		if (code == null)
		    code = ResponseCode.API_CODE_CALL_SUCCESS;
	    }

	    if (message == null || message.length() == 0) {
		message = Constants.API_MESSAGE_SUCCESS;
	    }

	    if (UtilValidate.isNotEmpty(serviceResults.get("fileMessage"))) {
		message = (String) serviceResults.get("fileMessage");
	    }

	    // JSONObject restResults =JSONObject.fromObject(serviceResults);
	    Gson gson = new Gson();

	    String restStr = "";
	    if (code.equals("\"0\"")) {
		if (serviceResults.containsKey("nfsList")) {
		    List list = (List) serviceResults.get("nfsList");
		    restStr = gson.toJson(list);
		    if (serviceResults.containsKey("totalCount")) {
			Integer totalCount = (Integer) serviceResults.get("totalCount");
			restStr = restStr + ",\"totalCount\":" + totalCount;
		    }
		} else if (serviceResults.containsKey("nfs")) {
		    Object nfs = serviceResults.get("nfs");
		    if (UtilValidate.isNotEmpty(nfs)) {
			// restStr = "\""+nfs.toString()+"\"";
			restStr = gson.toJson(nfs);
		    }
		} else {
		    restStr = gson.toJson(serviceResults);
		}

	    } else {
		restStr = "\"\"";
	    }
	    String body = restStr;// jsonArray.toString();
	    ApiResponse apiResponse = new ApiResponse(request, body, message, code);
	    if ("createApiUeditorFile".equals(serviceName)) {
		ResponseUtils.renderApiUeditor(response, request, serviceResults, apiResponse);
	    } else {
		ResponseUtils.renderApiJson(response, request, apiResponse);
	    }
	} catch (EventHandlerException e) {
	    Debug.logError(e, module);
	    if (e.getMessageList() == null) {
		return sendError(response, request, e.getMessage());
	    } else {
		return sendError(response, request, e.getMessageList());
	    }
	} catch (GenericEntityException e) {
	    Debug.logError(e, module);
	    if (e.getMessageList() == null) {
		return sendError(response, request, e.getMessage());
	    } else {
		return sendError(response, request, e.getMessageList());
	    }
	} catch (GenericServiceException e) {
	    Debug.logError(e, module);
	    if (e.getMessageList() == null) {
		return sendError(response, request, e.getMessage());
	    } else {
		return sendError(response, request, e.getMessageList());
	    }

	} catch (Exception e) {
	    Debug.logError(e, module);
	    return sendError(response, request, e.getMessage());
	}
	return "success";
    }

    public static String sendError(HttpServletResponse response, HttpServletRequest request, String errorMessage)
	    throws EventHandlerException {
	// setup the response
	return sendError(response, request, ServiceUtil.returnError(errorMessage));
    }

    public static String sendError(HttpServletResponse response, HttpServletRequest request, List<String> errorMessages)
	    throws EventHandlerException {
	return sendError(response, request, ServiceUtil.returnError(errorMessages.toString()));
    }

    public static String sendError(HttpServletResponse response, HttpServletRequest request, Object object)
	    throws EventHandlerException {
	response.setContentType("application/json");
	Gson gson = new Gson();
	String errorMessage = gson.toJson(object);
	// JSONObject restResults =JSONObject.fromObject(object);
	// String message = restResults.getString("errorMessage");
	Debug.log("errorMessage===" + errorMessage);
	String API_CODE_CALL_FAIL = ResponseCode.API_CODE_CALL_FAIL;
	String message = errorMessage;
	if (errorMessage.contains("check your USERNAME and PASSWORD.")) {
	    message = "您的账户在其他地方登录,请刷新页面重新登录!";
	    API_CODE_CALL_FAIL = "\"110\"";
	}
	if (errorMessage.contains("User authorization is required")) {
	    message = "您的账户在其他地方登录,请刷新页面重新登录!";
	    API_CODE_CALL_FAIL = "\"110\"";
	}
	if (errorMessage.contains("getLogOut")) {
	    message = "success";
	    API_CODE_CALL_FAIL = "\"0\"";
	}
	message = message.replaceAll(",", "");
	message = message.replaceAll("\"", "'");
	Debug.logError(message, module);
	ApiResponse apiResponse = new ApiResponse(request, "\"\"", message, API_CODE_CALL_FAIL);
	ResponseUtils.renderApiJson(response, request, apiResponse);
	// log the response message
	if (Debug.verboseOn()) {
	    Debug.logInfo("Response Message:\n" + message + "\n", module);
	}
	return "success";
    }

    public static Map<String, Object> checkRequestMultiPart(HttpServletRequest request) {
	boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
	Map<String, Object> multiPartMap = FastMap.newInstance();
	Delegator delegator = (Delegator) request.getAttribute("delegator");

	Enumeration<String> paramKeyEnum = UtilGenerics.cast(request.getParameterNames());
	while (paramKeyEnum.hasMoreElements()) {
	    String name = paramKeyEnum.nextElement();

	    Object value = null;
	    String[] paramArr = request.getParameterValues(name);
	    if (paramArr != null) {
		if (paramArr.length > 1) {
		    value = Arrays.asList(paramArr);
		} else {
		    value = paramArr[0];
		    // does the same thing basically, nothing better about it as far as I can see:
		    // value = request.getParameter(name);
		}
	    }
	    multiPartMap.put(name, value);
	}
	if (isMultiPart) {
	    // get the http upload configuration
	    String maxSizeStr = EntityUtilProperties.getPropertyValue("general.properties", "http.upload.max.size",
		    "-1", delegator);
	    long maxUploadSize = -1;
	    try {
		maxUploadSize = Long.parseLong(maxSizeStr);
	    } catch (NumberFormatException e) {
		Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1",
			module);
		maxUploadSize = -1;
	    }
	    // get the http size threshold configuration - files bigger than this will be
	    // temporarly stored on disk during upload
	    String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general.properties",
		    "http.upload.max.sizethreshold", "10240", delegator);
	    int sizeThreshold = 10240; // 10K
	    try {
		sizeThreshold = Integer.parseInt(sizeThresholdStr);
	    } catch (NumberFormatException e) {
		Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K",
			module);
		sizeThreshold = -1;
	    }
	    // directory used to temporarily store files that are larger than the configured
	    // size threshold
	    String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general.properties",
		    "http.upload.tmprepository", "runtime/tmp", delegator);
	    String encoding = request.getCharacterEncoding();
	    // check for multipart content types which may have uploaded items

	    ServletFileUpload upload = new ServletFileUpload(
		    new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));

	    // create the progress listener and add it to the session
	    FileUploadProgressListener listener = new FileUploadProgressListener();
	    upload.setProgressListener(listener);

	    request.getSession().setAttribute("uploadProgressListener", listener);

	    if (encoding != null) {
		upload.setHeaderEncoding(encoding);
	    }
	    upload.setSizeMax(maxUploadSize);

	    List<FileItem> uploadedItems = null;
	    try {
		uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
	    } catch (FileUploadException e) {
		// throw new EventHandlerException("Problems reading uploaded data", e);
	    }
	    if (uploadedItems != null) {
		for (FileItem item : uploadedItems) {
		    String fieldName = item.getFieldName();
		    if (fieldName.equals("file"))
			fieldName = "uploadFile";
		    if (item.isFormField() || item.getName() == null) {
			if (multiPartMap.containsKey(fieldName)) {
			    Object mapValue = multiPartMap.get(fieldName);
			    if (mapValue instanceof List<?>) {
				UtilGenerics.checkList(mapValue, Object.class).add(item.getString());
			    } else if (mapValue instanceof String) {
				List<String> newList = FastList.newInstance();
				newList.add((String) mapValue);
				newList.add(item.getString());
				multiPartMap.put(fieldName, newList);
			    } else {
				Debug.logWarning("Form field found [" + fieldName + "] which was not handled!", module);
			    }
			} else {
			    if (encoding != null) {
				try {
				    multiPartMap.put(fieldName, item.getString(encoding));
				} catch (java.io.UnsupportedEncodingException uee) {
				    Debug.logError(uee, "Unsupported Encoding, using deafault", module);
				    multiPartMap.put(fieldName, item.getString());
				}
			    } else {
				multiPartMap.put(fieldName, item.getString());
			    }
			}
		    } else {
			String fileName = item.getName();
			if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
			    // get just the file name IE and other browsers also pass in the local path
			    int lastIndex = fileName.lastIndexOf('\\');
			    if (lastIndex == -1) {
				lastIndex = fileName.lastIndexOf('/');
			    }
			    if (lastIndex > -1) {
				fileName = fileName.substring(lastIndex + 1);
			    }
			}
			multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
			multiPartMap.put(fieldName + "Size", Long.valueOf(item.getSize()));
			multiPartMap.put(fieldName + "FileName", fileName);
			multiPartMap.put(fieldName + "ContentType", item.getContentType());
		    }
		}
	    }
	}

	return multiPartMap;
    }

    public static String page(HttpServletRequest request, HttpServletResponse response) throws EventHandlerException {
	LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");

	Map<String, Object> serviceContext = FastMap.newInstance();
	Map<String, Object> inputFields = UtilHttp.getParameterMap(request, null, null);

	inputFields = JsonObjectUtils.mapInHandle(inputFields);

	String entityName = (String) inputFields.get("entityName");
	String orderBy = (String) inputFields.get("orderBy");

	Integer viewIndex = 0;
	Integer viewSize = 10;
	String pageNo = "1";
	String pageSize = "10";
	if (UtilValidate.isNotEmpty(inputFields.get("pageNo"))) {
	    pageNo = (String) inputFields.get("pageNo");
	    viewIndex = Integer.valueOf((String) inputFields.get("pageNo")) - 1;
	}

	if (UtilValidate.isNotEmpty(inputFields.get("pageSize"))) {
	    pageSize = (String) inputFields.get("pageSize");
	    viewSize = Integer.valueOf((String) inputFields.get("pageSize"));
	}

	serviceContext.put("inputFields", inputFields);
	serviceContext.put("entityName", entityName);
	serviceContext.put("orderBy", orderBy);
	serviceContext.put("viewIndex", viewIndex);
	serviceContext.put("viewSize", viewSize);
	serviceContext.put("noConditionFind", "Y");

	try {
	    Map<String, Object> serviceResults = dispatcher.runSync("performFindList", serviceContext);
	    serviceResults = JsonObjectUtils.optimizingResults(serviceResults);
	    List list = (List) serviceResults.get("list");
	    Gson gson = new Gson();
	    String restStr = gson.toJson(list);
	    // JSONArray restResults =JSONArray.fromObject(list);
	    Integer totalCount = (Integer) serviceResults.get("listSize");
	    String message = Constants.API_MESSAGE_SUCCESS;
	    String code = ResponseCode.API_CODE_CALL_SUCCESS;

	    if (UtilValidate.isNotEmpty(serviceResults.get("errorMessage"))) {
		message = Constants.API_STATUS_FAIL;
		code = ResponseCode.API_CODE_CALL_FAIL;
	    }
	    // String restStr = restResults.toString();
	    String body = restStr + ",\"totalCount\":" + totalCount;
	    body = body + ",\"pageNo\":" + pageNo;
	    body = body + ",\"pageSize\":" + pageSize;
	    ApiResponse apiResponse = new ApiResponse(request, body, message, code);
	    ResponseUtils.renderApiJson(response, request, apiResponse);

	} catch (GenericServiceException e) {
	    Debug.logError(e.getMessage(), module);
	}

	return "success";
    }

    public static String validateSign(HttpServletRequest request, String sign) {

	String result = "success";
	// 获取非签名,空字符,文件的参数名和参数值
	Map<String, String> param = getSignMap(request);
	if (UtilValidate.isEmpty(param)) {
	    param = getSignAttr(request);
	}
	// 密匙
	String appKey = UtilProperties.getPropertyValue("email", "appKey", "Sd6qkHm9o4LaVluYRX5pUFyNuiu2a8oi");
	String validateSign = PayUtil.createSign(param, appKey);
	if (sign == null || sign == "" || !sign.equals(validateSign)) {
	    result = "error";
	}

	return result;
    }
    
    public static String validateSha(HttpServletRequest request, String sign) throws UnsupportedEncodingException {
	String result = "success";
	// 获取非签名,空字符,文件的参数名和参数值
	Map<String, String> param = getSignMap(request);
	if (UtilValidate.isEmpty(param)) {
	    param = getSignAttr(request);
	}
	// 密匙
	String appKey = UtilProperties.getPropertyValue("email", "appKey", "Sd6qkHm9o4LaVluYRX5pUFyNuiu2a8oi");
//	String validateSign = PayUtil.createSha256(param, appKey);
	String newStr = PayUtil.getParamsStr(param, appKey);
	boolean s = PayUtil.doComparePosix(sign, newStr.getBytes("utf-8"));
	if(s ==false) {
	    result = "error"; 
	}
	return result;
    }
    
    public static void main(String[] args) throws UnsupportedEncodingException {
	//生成签名.
	Map<String,String> param = new HashMap();
	param.put("user", "1111");
	param.put("pass", "2222");
	String appKey = "Sd6qkHm9o4LaVluYRX5pUFyNuiu2a8oi";
	String validateSign = PayUtil.createSha256(param, appKey);
	System.out.println("validateSign =  " + validateSign);
	
	String sign = "$SHA-256$98$NMLUCGTLLVYO64NDKCDOFWFQL_ZLBJS2543WV6G0-QO";
	
	String newStr = PayUtil.getParamsStr(param, appKey);
	boolean s = PayUtil.doComparePosix(sign, newStr.getBytes("utf-8"));
	System.out.println(s);
    }
    
    
    @SuppressWarnings("rawtypes")
    public static Map<String, String> getSignAttr(HttpServletRequest request) {
	Map<String, String> param = new HashMap<String, String>();
	Map<String, Object> context = UtilHttp.getAttributeMap(request);
	Iterator it = context.entrySet().iterator();
	while (it.hasNext()) {
	    Map.Entry entry = (Map.Entry) it.next();
	    String pKey = (String) entry.getKey();
	    Object value = entry.getValue();
	    // sign和uploadFile不参与 值为空也不参与
	    if (!pKey.equals("thisRequestUri") && !pKey.equals("ftlServletContext")
		    && !pKey.equals("_FORWARDED_FROM_SERVLET_") && !pKey.equals("servletContext")
		    && !pKey.equals("delegator") && !pKey.equals("_SERVER_ROOT_URL_") && !pKey.equals("sign")
		    && !pKey.equals("_CONTROL_PATH_") && !pKey.equals("request") && !pKey.equals("response")
		    && !pKey.equals("targetRequestUri") && !pKey.equals("_REQUEST_HANDLER_") && !pKey.equals("security")
		    && !pKey.equals("_CONTEXT_ROOT_") && !pKey.equals("dispatcher") && !pKey.equals("uploadFile")
		    && !pKey.equals("onlineTypeId") && UtilValidate.isNotEmpty(value)) {
		param.put(pKey, String.valueOf(value));
	    }
	}
	return param;
    }

    public static Map<String, String> getSignMap(HttpServletRequest request) {
	Map<String, String> param = new HashMap<String, String>();
	Enumeration penum = (Enumeration) request.getParameterNames();
	while (penum.hasMoreElements()) {
	    String pKey = (String) penum.nextElement();
	    String value = request.getParameter(pKey);
	    // sign和uploadFile不参与 值为空也不参与
	    if (!pKey.equals("sign") && !pKey.equals("uploadFile") && UtilValidate.isNotEmpty(value)) {
		param.put(pKey, value);
	    }
	}
	return param;
    }
//	
//	public static String largeScreenService(HttpServletRequest request, HttpServletResponse response) throws IOException{
//		response.setHeader("Content-Type","text/event-stream");
//		response.setHeader("Cache-Control","no-cache");
//		response.setHeader("Connection","keep-alive");
//		   
//		
//		
//		Debug.log("largeScreenService start", module);
//		 String ip = getIpAdrress(request);
//		 Debug.log("request ip=   "+ip, module);
//		
//		 String id =request.getParameter("id");
//		 
//		Debug.log("request id=   "+request.getParameter("id"), module);
//		PrintWriter out = response.getWriter();
//		out.println("data: "+new java.util.Date(System.currentTimeMillis()).toString());
//		out.println();
//		out.flush();
//		Debug.log("largeScreenService end", module);
//		return "success";
//	}
//	private static String getIpAdrress(HttpServletRequest request) {
//        String Xip = request.getHeader("X-Real-IP");
//        String XFor = request.getHeader("X-Forwarded-For");
//        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
//            //多次反向代理后会有多个ip值，第一个ip才是真实ip
//            int index = XFor.indexOf(",");
//            if(index != -1){
//                return XFor.substring(0,index);
//            }else{
//                return XFor;
//            }
//        }
//        XFor = Xip;
//        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
//            return XFor;
//        }
//        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
//            XFor = request.getHeader("Proxy-Client-IP");
//        }
//        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
//            XFor = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
//            XFor = request.getHeader("HTTP_CLIENT_IP");
//        }
//        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
//            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
//        }
//        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
//            XFor = request.getRemoteAddr();
//        }
//        return XFor;
//    }
//	

}